﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.PlatForm.Dtos.VisualDev;
using JNPF.Basics.Models.VisualDev;
using JNPF.Utils;
using JNPF.Utils.Controller;
using JNPF.Utils.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 可视化开发
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2020.10.27
    /// </summary>
    [Route("api/VisualDevelopment")]
    public class VisualDevController : BaseApiController
    {
        private VisualDevBll visualDevBll = new VisualDevBll();
        private VisualDevModelDataBll visualDevModelDataBll = new VisualDevModelDataBll();
        private UserBll userBll = new UserBll();
        private DictionaryDataBll dictionaryDataBll = new DictionaryDataBll();

        #region GET

        /// <summary>
        /// 获取功能列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(VisualDevListQueryInput input)
        {
            var userList = (await userBll.GetList()).FindAll(t => t.EnabledMark.Equals(1));
            var data = await visualDevBll.GetList(input);
            var list = new ArrayList();
            foreach (var item in data.list)
            {
                var creatorUser = userList.Where(u => u.Id == item.CreatorUserId).FirstOrDefault();
                var dicts = SerializeHelper.Deserialize<Dictionary<string, object>>(SerializeHelper.Serialize(item));
                dicts.Add("CreatorUser", creatorUser.RealName + "/" + creatorUser.Account);
                var lastModifyUser = userList.Where(u => u.Id == item.LastModifyUserId && item.LastModifyUserId != null).FirstOrDefault();
                if (lastModifyUser != null)
                {
                    dicts.Add("LastModifyUser", lastModifyUser.RealName + "/" + lastModifyUser.Account);
                }
                else
                {
                    dicts.Add("LastModifyUser", "");
                }
                list.Add(SerializeHelper.Deserialize<VisualDevListOutput>(SerializeHelper.Serialize(dicts)));
            }
            var output = new PageResult()
            {
                list = list,
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 获取功能列表下拉框
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Selector")]
        public async Task<ResponseResult> GetSelector(VisualDevSelectorInput input)
        {
            var data = (await visualDevBll.GetList()).FindAll(x => x.Type == input.type && x.State == 1);
            var pList = new List<VisualDevSelectorOutput>();
            var output = data.Select(x => new VisualDevSelectorOutput()
            {
                fullName = x.FullName,
                id = x.Id,
                parentId = x.Category,
            }
            ).ToList();
            var parentIds = output.Select(x => x.parentId).ToList().Distinct();
            foreach (var item in parentIds)
            {
                var pData = (await dictionaryDataBll.GetInfo(item)).MapTo<VisualDevSelectorOutput>();
                pData.parentId = "-1";
                pList.Add(pData);
            }
            var treeList = output.Union(pList).ToList().ToTree("-1");
            return Success(new { list = treeList });
        }


        /// <summary>
        /// 获取功能信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = await visualDevBll.GetInfo(id);
            var output = data.MapTo<VisualDevInfoOutput>();
            return Success(output);
        }

        /// <summary>
        /// 获取命名空间
        /// </summary>
        [HttpGet("AreasName")]
        public async Task<ResponseResult> GetAreasName()
        {
            List<string> areasName = new List<string>();
            if (!Appsettings.app(new string[] { "JNPF_App", "CodeAreasName" }).ObjToBool())
            {
                areasName = Appsettings.app(new string[] { "JNPF_App", "CodeAreasName" }).Split(',').ToList();
            }
            return Success(areasName);
        }

        /// <summary>
        /// 获取表单主表属性下拉框
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/FormDataFields")]
        public async Task<ResponseResult> GetFormDataFields(string id)
        {
            var visualDevEntity = await visualDevBll.GetInfo(id);
            FormDataModel formData = visualDevEntity.FormData.ToObject<FormDataModel>();
            //多虑多余控件
            var newFields = visualDevModelDataBll.TemplateDataConversion(formData.fields);
            List<FieldsModel> fieldsModels = newFields.FindAll(x => !"".Equals(x.__vModel__) && !"table".Equals(x.__config__.jnpfKey) && !"relationForm".Equals(x.__config__.jnpfKey));
            var output = fieldsModels.Select(x => new VisualDevFormDataFieldsOutput()
            {
                label = x.__config__.label,
                vmodel = x.__vModel__
            }).ToList();
            return Success(new { list = output });
        }

        /// <summary>
        /// 获取表单主表属性列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        [HttpGet("{id}/FieldDataSelect")]
        public async Task<ResponseResult> GetFieldDataSelect(string id, string field)
        {
            var visualDevEntity = await visualDevBll.GetInfo(id);
            FormDataModel formData = visualDevEntity.FormData.ToObject<FormDataModel>();
            //多虑多余控件
            var newFields = visualDevModelDataBll.TemplateDataConversion(formData.fields);
            var newFieLdsModelList = newFields.FindAll(x => field.Equals(x.__vModel__));
            formData.fields = newFieLdsModelList;
            visualDevEntity.FormData = formData.ToJson();
            //获取值 无分页
            VisualDevModelListQueryInput listQueryInput = new VisualDevModelListQueryInput
            {
                dataType = "1"
            };
            var realList = (await visualDevModelDataBll.GetListResult(visualDevEntity, listQueryInput)).list;
            var output = realList.FindAll(x => x.ContainsKey(field)).Select(x => new VisualDevFieldDataSelectOutput()
            {
                id = x["id"].ToString(),
                fullName = x[field].IsEmpty() ? "" : x[field].ToString()
            }).ToList();
            return Success(new { list = output });
        }

        #endregion

        #region POST

        /// <summary>
        /// 新建功能信息
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] VisualDevCrInput input)
        {
            var entity = input.MapTo<VisualDevEntity>();
            await visualDevBll.Create(entity);
            return Success("新建成功");
        }

        /// <summary>
        /// 修改接口
        /// </summary>
        /// <param name="id">主键id</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] VisualDevUpInput input)
        {
            var entity = input.MapTo<VisualDevEntity>();
            var isOk = await visualDevBll.Update(id, entity);
            return isOk > 0 ? Success("修改成功") : Error("修改失败");
        }

        /// <summary>
        /// 删除接口
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await visualDevBll.GetInfo(id);
            var isOk = await visualDevBll.Delete(entity);
            return isOk > 0 ? Success("删除成功") : Error("删除失败");
        }

        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpPost("{id}/Actions/Copy")]
        public async Task<ResponseResult> ActionsCopy(string id)
        {
            var entity = await visualDevBll.GetInfo(id);
            entity.FullName = entity.FullName + "_副本";
            entity.EnCode = entity.EnCode + "_1";
            entity.State = 0;
            entity.LastModifyTime = null;
            entity.LastModifyUserId = null;
            var isOk = await visualDevBll.Create(entity);
            return isOk > 0 ? Success("复制成功") : Error("复制失败");
        }

        /// <summary>
        /// 下载代码
        /// </summary>
        [HttpPost("{id}/Actions/DownloadCode")]
        public async Task<ResponseResult> DownloadCode(string id, [FromBody] DownloadCodeFormInput downloadCodeForm)
        {
            UserInfo userInfo = UserProvider.Instance.Get();
            VisualDevEntity entity = await visualDevBll.GetInfo(id);
            if (entity != null)
            {
                if (!StringHelper.IsNullOrEmpty(entity.Tables))
                {
                    DictionaryDataEntity dentity = await dictionaryDataBll.GetInfo(downloadCodeForm.module);
                    var model = entity.FormData.ToObject<FormDataModel>();
                    model.className = downloadCodeForm.className.Substring(0, 1).ToUpper() + downloadCodeForm.className.Substring(1);
                    model.areasName = downloadCodeForm.module;
                    //生成模板存储路径
                    model.serviceDirectory = Appsettings.app(new string[] { "JNPF_App", "TemplateCodePath" });
                    string fileName = CommonHelper.Guid;
                    //判断子表名称
                    var childTb = new List<string>();
                    if (!StringHelper.IsNullOrEmpty(downloadCodeForm.subClassName))
                    {
                        childTb = new List<string>(downloadCodeForm.subClassName.Split(','));
                    }
                    //子表名称去重
                    HashSet<string> set = new HashSet<string>(childTb);
                    bool result = childTb.Count == set.Count ? true : false;
                    if (!result)
                    {
                        //return ActionResult.fail("名称不能重复");
                    }
                    //Web表单
                    if (entity.Type == 4)
                    {
                        //生成前端页面
                        //生成模型
                        await visualDevBll.GetFormModelTemplates(fileName, entity, childTb, downloadCodeForm.module);

                        //生成ApiController

                        //生出Bll
                        //生出IService于Service

                    }
                    //流程表单
                    if (entity.Type == 3)
                    {
                        downloadCodeForm.module = "WorkFlowForm";
                        visualDevBll.GetFlowModelTemplates(fileName, entity, childTb, downloadCodeForm.module);
                    }
                    //移动开发
                    if (entity.Type == 2)
                    {

                    }
                    //app代码生成器
                    if (entity.Type == 5)
                    {
                        visualDevBll.GetAppModelTemplates(fileName, entity, childTb, downloadCodeForm.module);
                    }
                    string randPath = ConfigurationKey.CodeGeneratorFilePath + fileName;
                    string downloadPath = ConfigurationKey.CodeGeneratorFilePath + fileName + ".zip";
                    //将第一个参数路径下的所有文件以及文件夹打包压缩成第二个参数的路径
                    ZipFile.CreateFromDirectory(randPath, downloadPath);
                    return Success(new { name = fileName, url = "/api/Common/Download?encryption=" + userInfo.Id + "|" + fileName + ".zip|codeGenerator" });
                    //return Success("");
                }
            }
            return Success("");
        }

        /// <summary>
        /// 预览代码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="downloadCodeForm"></param>
        /// <returns></returns>
        [HttpPost("{id}/Actions/CodePreview")]
        public async Task<ResponseResult> CodePreview(string id, [FromBody] DownloadCodeFormInput downloadCodeForm)
        {
            UserInfo userInfo = UserProvider.Instance.Get();
            VisualDevEntity entity = await visualDevBll.GetInfo(id);
            if (entity != null)
            {
                if (!StringHelper.IsNullOrEmpty(entity.Tables))
                {
                    DictionaryDataEntity dentity = await dictionaryDataBll.GetInfo(downloadCodeForm.module);
                    var model = TemplateKeywordsHelper.ReplaceKeywords(entity.FormData).ToObject<FormDataModel>();
                    model.className = downloadCodeForm.className.Substring(0, 1).ToUpper() + downloadCodeForm.className.Substring(1);
                    model.areasName = downloadCodeForm.module;
                    //生成模板存储路径
                    model.serviceDirectory = Appsettings.app(new string[] { "JNPF_App", "TemplateCodePath" });
                    string fileName = CommonHelper.Guid;
                    //判断子表名称
                    var childTb = new List<string>();
                    if (!StringHelper.IsNullOrEmpty(downloadCodeForm.subClassName))
                    {
                        childTb = new List<string>(downloadCodeForm.subClassName.Split(','));
                    }
                    //子表名称去重
                    HashSet<string> set = new HashSet<string>(childTb);
                    bool result = childTb.Count == set.Count ? true : false;
                    if (!result)
                    {
                        //return ActionResult.fail("名称不能重复");
                    }
                    //Web表单
                    if (entity.Type == 4)
                    {
                        //生成前端页面
                        //生成模型
                        await visualDevBll.GetFormModelTemplates(fileName, entity, childTb, downloadCodeForm.module);
                    }
                    //流程表单
                    if (entity.Type == 3)
                    {

                        downloadCodeForm.module = "WorkFlowForm";
                        visualDevBll.GetFlowModelTemplates(fileName, entity, childTb, downloadCodeForm.module);
                    }
                    //移动开发
                    if (entity.Type == 2)
                    {
                    }
                    //app代码生成器
                    if (entity.Type == 5)
                    {
                        visualDevBll.GetAppModelTemplates(fileName, entity, childTb, downloadCodeForm.module);
                    }
                    string randPath = ConfigurationKey.CodeGeneratorFilePath + fileName;
                    var dataList = visualDevBll.priviewCode(randPath);
                    if (dataList == null && dataList.Count == 0)
                    {
                        return Error("预览失败，数据不存在");
                    }
                    var output = new
                    {
                        list = dataList
                    };
                    return Success(output);
                }
            }
            return Success("");
        }
        #endregion
    }
}
